package com.examples.gateway.helper.filter;

import com.examples.core.req.ExamHeader;
import com.examples.gateway.helper.Constants;
import com.examples.gateway.helper.config.GatewayHelperProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 向下层服务传递 Token
 * @author Dai YaLu
 */
@Slf4j
public class AddJwtTokenFilter extends AbstractGlobalHelperFilter {

    @Autowired
    private GatewayHelperProperties properties;

    @Override
    public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        GatewayHelperProperties.TokenResolver resolver = properties.getTokenResolver();
        ExamHeader user = exchange.getAttribute(Constants.EXAMPLES_GATEWAY_USER_DETAIL);
        // 生成JWT Token
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        ServerHttpRequest request = exchange
                .getRequest()
                .mutate()
                .header(resolver.getHeaderKey(), token).build();
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return 50;
    }
}
